# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 服务端（RPC Server）.py
# @Author: dongguangwen
# @Date  : 2025-04-12 12:21
import pika


def fib(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fib(n - 1) + fib(n - 2)


credentials = pika.PlainCredentials('admin', 'password')
connection = pika.BlockingConnection(
    pika.ConnectionParameters('192.168.1.119', credentials=credentials, virtual_host='my_vhost'))
channel = connection.channel()

channel.queue_declare(queue="rpc_queue")


def on_request(ch, method, props, body):
    n = int(body)
    print(f"[✔] 收到RPC请求：fib({n})")

    import time
    time.sleep(20)

    response = fib(n)

    # 返回响应消息
    ch.basic_publish(
        exchange="",
        routing_key=props.reply_to,
        properties=pika.BasicProperties(correlation_id=props.correlation_id),
        body=str(response)
    )
    ch.basic_ack(delivery_tag=method.delivery_tag)


channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue="rpc_queue", on_message_callback=on_request)

print("[🔁] 正在等待 RPC 请求...")
channel.start_consuming()
